package com.woniu.market_stall_web.service;

import com.woniu.market_stall_web.entity.Order;
import com.woniu.market_stall_web.entity.Stall;
import com.woniu.market_stall_web.entity.User;
import com.woniu.market_stall_web.mapper.OrderMapper;
import com.woniu.market_stall_web.mapper.StallAuctionMapper;
import com.woniu.market_stall_web.mapper.StallMapper;
import com.woniu.market_stall_web.mapper.UserMapper;
import com.woniu.market_stall_web.vo.AuctionRoomVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class AuctionRoomService {

    @Autowired
    StallAuctionMapper stallAuctionMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    StallMapper stallMapper;

    @Autowired
    UserMapper userMapper;



    public List<AuctionRoomVo> queryRoomByStallId(int stallId ,String username ){

        return stallAuctionMapper.selectRoomByStallId(stallId ,username);

    }

    public void signUpByUsername(int stallId , String username) {
        stallAuctionMapper.insertBidUser(stallId ,username );
    }

    public void insertBidPrice(int stallId, String username, int bidPrice) {
        stallAuctionMapper.insertBidPrice(stallId , username , bidPrice ,new Date());
    }

    public int queryMaxBidPrice(int stallId) {
       return stallAuctionMapper.selectMaxBidPrice(stallId);
    }

    @Transactional
    public void insertAuctionOrder(int bidPrice , int stallId){

        Stall stall = stallMapper.selectByPrimaryKey(stallId);
        AuctionRoomVo auctionRoomVo = stallAuctionMapper.selectWinnerByBidPriceAndStallId(stallId);
        User user = userMapper.selectUserByName(auctionRoomVo.getUsername());

        Order order = new Order();
        order.setOrderId(System.currentTimeMillis()+"");
        order.setMarketId(stall.getMarketId());
        order.setOrderPrice(auctionRoomVo.getBidPrice());
        order.setCash(stall.getpCash());
        order.setInsertTime(new Date());
        order.setUserId(user.getId());
        order.setStallId(stallId);

        //生成订单
        orderMapper.insertAuctionOrder(order);

        //将竞拍摊位置为 已结束
        stallMapper.updateAuctionStallStatus(stallId , user.getId());
    }

    public int modifyAuctionStallStatus(int stallId) {
        return stallMapper.modifyAuctionStallStatus(stallId);
    }



}
